// 任务数据结构
class Task {
  constructor(id, title, description = '', deadline = null, priority = 'medium', quadrant = null, completed = false) {
    this.id = id;
    this.title = title;
    this.description = description;
    this.deadline = deadline;
    this.priority = priority; // 'low', 'medium', 'high'
    this.quadrant = quadrant; // 1, 2, 3, 4 或 null (未分配)
    this.completed = completed;
    this.createdAt = new Date();
  }
}

// 任务管理器
class TaskManager {
  constructor() {
    this.tasks = [];
    this.loadTasks();
    this.initializeDragAndDrop();
    this.updateTaskCounts();
    this.filterOptions = {
      status: [],      // 'completed' 或 'uncompleted'
      priority: [],    // 'high', 'medium', 'low'
      deadline: [],    // 'today', 'tomorrow', 'thisWeek', 'nextWeek', 'noDeadline'
      dateRange: {     // 自定义日期范围
        from: null,
        to: null
      }
    };
    this.isFiltering = false;
    
    // 加载保存的主题
    this.loadTheme();
  }

  // 从本地存储加载任务
  loadTasks() {
    const savedTasks = localStorage.getItem('quadrantTasks');
    if (savedTasks) {
      try {
        const parsedTasks = JSON.parse(savedTasks);
        this.tasks = parsedTasks.map(task => {
          return new Task(
            task.id,
            task.title,
            task.description,
            task.deadline ? new Date(task.deadline) : null,
            task.priority,
            task.quadrant,
            task.completed
          );
        });
        this.renderAllTasks();
        this.renderUnassignedTasks();
      } catch (error) {
        console.error('加载任务失败:', error);
        this.tasks = this.getInitialTasks();
        this.renderAllTasks();
        this.renderUnassignedTasks();
      }
    } else {
      this.tasks = this.getInitialTasks();
      this.renderAllTasks();
      this.renderUnassignedTasks();
    }
  }

  // 获取初始示例任务
  getInitialTasks() {
    return [
      new Task('1', '完成项目报告', '完成四象限项目的详细报告', new Date(Date.now() + 24 * 60 * 60 * 1000), 'high', 1),
      new Task('2', '学习新技术', '学习HTML5和CSS3的新特性', new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), 'medium', 2),
      new Task('3', '回复邮件', '回复所有未读邮件', new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), 'medium', 3),
      new Task('4', '整理文件夹', '整理电脑桌面和文件夹', new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), 'low', 4),
      new Task('5', '制定学习计划', '为接下来的月度学习制定详细计划', null, 'medium', null)
    ];
  }

  // 保存任务到本地存储
  saveTasks() {
    localStorage.setItem('quadrantTasks', JSON.stringify(this.tasks));
  }

  // 添加新任务
  addTask(data) {
    const newTask = new Task(
      Date.now().toString(),
      data.title,
      data.description || '',
      data.deadline ? new Date(data.deadline) : null,
      data.priority || 'medium',
      data.quadrant ? parseInt(data.quadrant) : null,
      false
    );
    
    this.tasks.push(newTask);
    
    if (newTask.quadrant) {
      this.renderTask(newTask);
    } else {
      this.renderUnassignedTasks(); // 更新未分配任务列表
    }
    
    this.saveTasks();
    this.updateTaskCounts();
  }

  // 编辑任务
  editTask(taskId, data) {
    const oldTask = this.getTaskById(taskId);
    const oldQuadrant = oldTask ? oldTask.quadrant : null;
    
    this.tasks = this.tasks.map(task => {
      if (task.id === taskId) {
        return {
          ...task,
          title: data.title,
          description: data.description || '',
          deadline: data.deadline ? new Date(data.deadline) : null,
          priority: data.priority,
          quadrant: data.quadrant !== undefined ? parseInt(data.quadrant) : task.quadrant
        };
      }
      return task;
    });
    
    this.saveTasks();
    
    // 如果任务从未分配变为已分配，或者从已分配变为未分配，或者在不同象限之间移动
    const updatedTask = this.getTaskById(taskId);
    const newQuadrant = updatedTask ? updatedTask.quadrant : null;
    
    if (oldQuadrant !== newQuadrant) {
      this.renderAllTasks();
      this.renderUnassignedTasks();
    } else if (newQuadrant === null) {
      this.renderUnassignedTasks();
    } else {
      this.renderAllTasks();
    }
  }

  // 删除任务
  deleteTask(taskId) {
    const taskToDelete = this.getTaskById(taskId);
    this.tasks = this.tasks.filter(task => task.id !== taskId);
    this.saveTasks();
    
    if (taskToDelete && taskToDelete.quadrant === null) {
      this.renderUnassignedTasks();
    } else {
      this.renderAllTasks();
    }
    
    this.updateTaskCounts();
  }

  // 获取任务
  getTaskById(taskId) {
    return this.tasks.find(task => task.id === taskId);
  }

  // 切换任务完成状态
  toggleTaskStatus(taskId) {
    this.tasks = this.tasks.map(task => {
      if (task.id === taskId) {
        return { ...task, completed: !task.completed };
      }
      return task;
    });
    
    this.saveTasks();
    this.renderAllTasks();
  }

  // 移动任务到不同象限
  moveTask(taskId, newQuadrant) {
    this.tasks = this.tasks.map(task => {
      if (task.id === taskId) {
        return { ...task, quadrant: parseInt(newQuadrant) };
      }
      return task;
    });
    
    this.saveTasks();
    this.renderAllTasks();
    this.renderUnassignedTasks();
  }

  // 渲染所有任务
  renderAllTasks() {
    // 清空所有象限的任务
    for (let i = 1; i <= 4; i++) {
      const container = document.getElementById(`tasks-${i}`);
      container.innerHTML = '';
    }
    
    // 获取任务列表，如果正在筛选，使用过滤后的列表
    const tasksToRender = this.isFiltering ? this.getFilteredTasks() : this.tasks;
    
    // 渲染每个任务到对应象限
    tasksToRender.forEach(task => {
      if (task.quadrant !== null) {
        this.renderTask(task);
      }
    });
    
    this.updateTaskCounts();
    this.updateFilterIndicator();
  }

  // 渲染单个任务
  renderTask(task) {
    if (!task.quadrant) return; // 如果没有指定象限，则不渲染
    
    const container = document.getElementById(`tasks-${task.quadrant}`);
    const template = document.getElementById('task-template');
    const taskElement = template.content.cloneNode(true).querySelector('.task');
    
    // 设置任务ID，用于识别
    taskElement.setAttribute('data-task-id', task.id);
    taskElement.setAttribute('data-quadrant', task.quadrant);
    
    // 设置任务内容
    const titleElement = taskElement.querySelector('.task-title');
    titleElement.textContent = task.title;
    
    const checkboxElement = taskElement.querySelector('.task-checkbox');
    checkboxElement.checked = task.completed;
    
    // 如果任务完成，添加完成样式
    if (task.completed) {
      taskElement.classList.add('completed');
    }
    
    // 如果任务重要，添加重要样式
    if (task.priority === 'high') {
      taskElement.classList.add('important');
    }
    
    // 设置截止日期
    const deadlineElement = taskElement.querySelector('.task-deadline');
    if (task.deadline) {
      const formattedDate = task.deadline.toLocaleDateString();
      deadlineElement.textContent = `截止: ${formattedDate}`;
      
      // 如果截止日期在24小时内且任务未完成，添加紧急样式
      const isDeadlineSoon = task.deadline.getTime() - new Date().getTime() < 24 * 60 * 60 * 1000;
      if (isDeadlineSoon && !task.completed) {
        taskElement.classList.add('deadline-soon');
      }
    } else {
      deadlineElement.style.display = 'none';
    }
    
    // 设置优先级标签
    const priorityBadge = taskElement.querySelector('.priority-badge');
    if (task.priority === 'high') {
      priorityBadge.textContent = '高';
      priorityBadge.classList.add('priority-high');
    } else if (task.priority === 'medium') {
      priorityBadge.textContent = '中';
      priorityBadge.classList.add('priority-medium');
    } else {
      priorityBadge.textContent = '低';
      priorityBadge.classList.add('priority-low');
    }
    
    // 设置任务描述
    const descriptionElement = taskElement.querySelector('.task-description');
    if (task.description) {
      descriptionElement.textContent = task.description;
    } else {
      descriptionElement.textContent = '没有描述';
    }
    
    // 添加展开/折叠功能
    const expandButton = taskElement.querySelector('.expand-button');
    expandButton.addEventListener('click', () => {
      descriptionElement.classList.toggle('show');
      expandButton.classList.toggle('expanded');
    });
    
    // 添加任务状态切换功能
    checkboxElement.addEventListener('change', () => {
      this.toggleTaskStatus(task.id);
    });
    
    // 添加拖拽属性
    taskElement.setAttribute('draggable', 'true');
    
    // 添加编辑按钮事件
    const editButton = taskElement.querySelector('.edit-button');
    editButton.addEventListener('click', (e) => {
      e.stopPropagation();
      this.showEditTaskModal(task.id);
    });
    
    // 添加删除按钮事件
    const deleteButton = taskElement.querySelector('.delete-button');
    deleteButton.addEventListener('click', (e) => {
      e.stopPropagation();
      this.showDeleteConfirmModal(task.id);
    });
    
    // 将任务添加到容器
    container.appendChild(taskElement);
  }

  // 渲染未分配任务
  renderUnassignedTasks() {
    const container = document.getElementById('unassigned-tasks-list');
    container.innerHTML = '';
    
    // 获取任务列表，如果正在筛选，使用过滤后的列表
    let unassignedTasks = this.isFiltering 
      ? this.getFilteredTasks().filter(task => task.quadrant === null)
      : this.tasks.filter(task => task.quadrant === null);
    
    if (unassignedTasks.length === 0) {
      const emptyMessage = document.createElement('div');
      emptyMessage.className = 'empty-message';
      emptyMessage.textContent = this.isFiltering 
        ? '没有符合筛选条件的未分配任务' 
        : '暂无未分配任务';
      container.appendChild(emptyMessage);
      return;
    }
    
    unassignedTasks.forEach(task => {
      const template = document.getElementById('unassigned-task-template');
      const taskElement = template.content.cloneNode(true).querySelector('.unassigned-task');
      
      // 设置任务ID，用于识别
      taskElement.setAttribute('data-task-id', task.id);
      
      // 设置任务内容
      const titleElement = taskElement.querySelector('.unassigned-task-title');
      titleElement.textContent = task.title;
      
      // 设置截止日期
      const deadlineElement = taskElement.querySelector('.unassigned-task-deadline');
      if (task.deadline) {
        const formattedDate = task.deadline.toLocaleDateString();
        deadlineElement.textContent = `截止: ${formattedDate}`;
        
        // 如果截止日期在24小时内，添加紧急样式
        const isDeadlineSoon = task.deadline.getTime() - new Date().getTime() < 24 * 60 * 60 * 1000;
        if (isDeadlineSoon) {
          deadlineElement.classList.add('deadline-soon');
        }
      } else {
        deadlineElement.style.display = 'none';
      }
      
      // 设置描述
      const descriptionElement = taskElement.querySelector('.unassigned-task-description');
      if (task.description) {
        descriptionElement.textContent = task.description;
      } else {
        descriptionElement.textContent = '没有描述';
      }
      
      // 添加分配按钮事件
      const assignButton = taskElement.querySelector('.assign-button');
      assignButton.addEventListener('click', () => {
        this.showAssignTaskModal(task.id);
      });
      
      // 添加编辑按钮事件
      const editButton = taskElement.querySelector('.edit-button');
      editButton.addEventListener('click', () => {
        this.showEditTaskModal(task.id);
      });
      
      // 添加删除按钮事件
      const deleteButton = taskElement.querySelector('.delete-button');
      deleteButton.addEventListener('click', () => {
        this.showDeleteConfirmModal(task.id);
      });
      
      // 将任务添加到容器
      container.appendChild(taskElement);
    });
  }

  // 更新每个象限的任务数量显示
  updateTaskCounts() {
    for (let i = 1; i <= 4; i++) {
      const count = this.tasks.filter(task => task.quadrant === i).length;
      const countElement = document.getElementById(`count-${i}`);
      countElement.textContent = `${count} 任务`;
    }
    
    // 更新未分配任务数量标记
    const unassignedCount = this.tasks.filter(task => task.quadrant === null).length;
    const unassignedButton = document.getElementById('unassigned-button');
    
    if (unassignedCount > 0) {
      // 如果还没有任务数量标记，就创建一个
      let countBadge = unassignedButton.querySelector('.count-badge');
      if (!countBadge) {
        countBadge = document.createElement('span');
        countBadge.className = 'count-badge';
        unassignedButton.appendChild(countBadge);
      }
      countBadge.textContent = unassignedCount;
    } else {
      // 如果没有未分配任务，移除数量标记
      const countBadge = unassignedButton.querySelector('.count-badge');
      if (countBadge) {
        unassignedButton.removeChild(countBadge);
      }
    }
  }

  // 初始化拖放功能
  initializeDragAndDrop() {
    // 在这里我们将会实现HTML5原生拖放API
    document.addEventListener('dragstart', (e) => {
      if (e.target.classList.contains('task')) {
        e.dataTransfer.setData('text/plain', e.target.getAttribute('data-task-id'));
        e.target.classList.add('dragging');
        
        // 为了更好的视觉效果，设置拖动图像
        const img = new Image();
        img.src = '';
        e.dataTransfer.setDragImage(img, 0, 0);
      }
    });
    
    document.addEventListener('dragend', (e) => {
      if (e.target.classList.contains('task')) {
        e.target.classList.remove('dragging');
      }
    });
    
    // 为每个任务容器添加拖放事件监听器
    for (let i = 1; i <= 4; i++) {
      const container = document.getElementById(`tasks-${i}`);
      
      container.addEventListener('dragover', (e) => {
        e.preventDefault();
        container.classList.add('drag-over');
      });
      
      container.addEventListener('dragleave', () => {
        container.classList.remove('drag-over');
      });
      
      container.addEventListener('drop', (e) => {
        e.preventDefault();
        container.classList.remove('drag-over');
        
        const taskId = e.dataTransfer.getData('text/plain');
        const newQuadrant = container.id.split('-')[1];
        
        this.moveTask(taskId, newQuadrant);
      });
    }
  }

  // 显示编辑任务模态框
  showEditTaskModal(taskId) {
    const task = this.getTaskById(taskId);
    if (!task) return;
    
    // 填充表单
    document.getElementById('edit-task-id').value = task.id;
    document.getElementById('edit-task-title').value = task.title;
    document.getElementById('edit-task-desc').value = task.description || '';
    document.getElementById('edit-task-priority').value = task.priority;
    
    // 如果任务有象限，设置象限选择器
    if (document.getElementById('edit-task-quadrant')) {
      document.getElementById('edit-task-quadrant').value = task.quadrant || '';
    }
    
    // 设置日期
    if (task.deadline) {
      const dateStr = task.deadline.toISOString().split('T')[0];
      document.getElementById('edit-task-deadline').value = dateStr;
    } else {
      document.getElementById('edit-task-deadline').value = '';
    }
    
    // 显示模态框
    document.getElementById('edit-task-modal').classList.add('show');
  }
  
  // 显示删除确认模态框
  showDeleteConfirmModal(taskId) {
    document.getElementById('delete-task-id').value = taskId;
    document.getElementById('delete-confirm-modal').classList.add('show');
  }
  
  // 显示分配任务模态框
  showAssignTaskModal(taskId) {
    document.getElementById('assign-task-id').value = taskId;
    document.getElementById('assign-task-modal').classList.add('show');
  }
  
  // 添加未分配任务
  addUnassignedTask(data) {
    const taskData = {
      ...data,
      quadrant: null // 未分配任务没有象限
    };
    
    this.addTask(taskData);
  }
  
  // 分配任务到象限
  assignTask(taskId, quadrant) {
    this.moveTask(taskId, quadrant);
  }

  // 更新筛选指示器
  updateFilterIndicator() {
    const filterButton = document.querySelector('.filter-button');
    
    if (this.isFiltering) {
      // 添加筛选激活状态
      document.body.classList.add('filter-active');
      
      // 添加筛选指示点
      let indicator = filterButton.querySelector('.filter-indicator');
      if (!indicator) {
        indicator = document.createElement('span');
        indicator.className = 'filter-indicator';
        filterButton.appendChild(indicator);
      }
    } else {
      // 移除筛选激活状态
      document.body.classList.remove('filter-active');
      
      // 移除筛选指示点
      const indicator = filterButton.querySelector('.filter-indicator');
      if (indicator) {
        filterButton.removeChild(indicator);
      }
    }
  }
  
  // 应用筛选条件
  applyFilter(filterOptions) {
    this.filterOptions = filterOptions;
    this.isFiltering = this.isFilterActive();
    this.renderAllTasks();
    this.renderUnassignedTasks();
  }
  
  // 重置筛选条件
  resetFilter() {
    this.filterOptions = {
      status: [],
      priority: [],
      deadline: [],
      dateRange: {
        from: null,
        to: null
      }
    };
    this.isFiltering = false;
    this.renderAllTasks();
    this.renderUnassignedTasks();
  }
  
  // 判断是否有生效的筛选条件
  isFilterActive() {
    return (
      this.filterOptions.status.length > 0 ||
      this.filterOptions.priority.length > 0 ||
      this.filterOptions.deadline.length > 0 ||
      (this.filterOptions.dateRange.from !== null && this.filterOptions.dateRange.to !== null)
    );
  }
  
  // 获取过滤后的任务列表
  getFilteredTasks() {
    return this.tasks.filter(task => {
      // 筛选状态
      if (this.filterOptions.status.length > 0) {
        const statusMatch = (
          (this.filterOptions.status.includes('completed') && task.completed) ||
          (this.filterOptions.status.includes('uncompleted') && !task.completed)
        );
        if (!statusMatch) return false;
      }
      
      // 筛选优先级
      if (this.filterOptions.priority.length > 0) {
        if (!this.filterOptions.priority.includes(task.priority)) return false;
      }
      
      // 筛选截止日期
      if (this.filterOptions.deadline.length > 0 || 
          (this.filterOptions.dateRange.from && this.filterOptions.dateRange.to)) {
        
        // 无截止日期选项
        if (this.filterOptions.deadline.includes('noDeadline') && !task.deadline) {
          return true;
        }
        
        // 如果任务没有截止日期且未选择"无截止日期"选项，则不符合条件
        if (!task.deadline && !this.filterOptions.deadline.includes('noDeadline')) {
          return false;
        }
        
        // 如果任务有截止日期，检查是否符合时间范围
        if (task.deadline) {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          
          const tomorrow = new Date(today);
          tomorrow.setDate(tomorrow.getDate() + 1);
          
          const taskDate = new Date(task.deadline);
          taskDate.setHours(0, 0, 0, 0);
          
          // 检查预设日期条件
          if (this.filterOptions.deadline.length > 0) {
            let dateMatches = false;
            
            if (this.filterOptions.deadline.includes('today')) {
              if (taskDate.getTime() === today.getTime()) dateMatches = true;
            }
            
            if (this.filterOptions.deadline.includes('tomorrow')) {
              if (taskDate.getTime() === tomorrow.getTime()) dateMatches = true;
            }
            
            if (this.filterOptions.deadline.includes('thisWeek')) {
              const endOfWeek = new Date(today);
              endOfWeek.setDate(endOfWeek.getDate() + (7 - today.getDay()));
              
              if (taskDate >= today && taskDate <= endOfWeek) dateMatches = true;
            }
            
            if (this.filterOptions.deadline.includes('nextWeek')) {
              const startOfNextWeek = new Date(today);
              startOfNextWeek.setDate(startOfNextWeek.getDate() + (7 - today.getDay() + 1));
              
              const endOfNextWeek = new Date(startOfNextWeek);
              endOfNextWeek.setDate(endOfNextWeek.getDate() + 6);
              
              if (taskDate >= startOfNextWeek && taskDate <= endOfNextWeek) dateMatches = true;
            }
            
            if (!dateMatches) return false;
          }
          
          // 检查自定义日期范围
          if (this.filterOptions.dateRange.from && this.filterOptions.dateRange.to) {
            const fromDate = new Date(this.filterOptions.dateRange.from);
            fromDate.setHours(0, 0, 0, 0);
            
            const toDate = new Date(this.filterOptions.dateRange.to);
            toDate.setHours(23, 59, 59, 999);
            
            if (!(taskDate >= fromDate && taskDate <= toDate)) return false;
          }
        }
      }
      
      // 通过所有筛选条件
      return true;
    });
  }

  // 导入任务数据
  importTasks(taskData) {
    try {
      // 解析任务数据，创建Task对象
      const importedTasks = taskData.map(task => {
        return new Task(
          task.id || Date.now().toString() + Math.random().toString(36).substr(2, 5),
          task.title,
          task.description || '',
          task.deadline ? new Date(task.deadline) : null,
          task.priority || 'medium',
          task.quadrant,
          task.completed || false
        );
      });
      
      // 将导入的任务添加到现有任务列表中
      // 避免ID冲突，如果有相同ID的任务，使用导入的任务替换现有任务
      const existingIds = new Set(this.tasks.map(task => task.id));
      const newTasks = importedTasks.filter(task => !existingIds.has(task.id));
      
      // 更新冲突的任务
      const updatedTasks = this.tasks.map(task => {
        const importedTask = importedTasks.find(importedTask => importedTask.id === task.id);
        return importedTask || task;
      });
      
      // 合并任务列表
      this.tasks = [...updatedTasks, ...newTasks];
      
      // 保存并渲染
      this.saveTasks();
      this.renderAllTasks();
      this.renderUnassignedTasks();
      
      return {
        success: true,
        message: `成功导入 ${importedTasks.length} 个任务`,
        importedCount: importedTasks.length
      };
    } catch (error) {
      console.error('导入任务失败:', error);
      return {
        success: false,
        message: '导入失败: ' + error.message
      };
    }
  }

  // 加载保存的主题
  loadTheme() {
    const savedTheme = localStorage.getItem('quadrantTheme');
    if (savedTheme) {
      this.applyTheme(savedTheme);
    }
  }
  
  // 应用主题
  applyTheme(themeName) {
    // 移除所有主题类
    document.body.classList.remove('theme-blue', 'theme-green', 'theme-purple', 'theme-dark');
    
    // 如果不是默认主题，添加对应的类
    if (themeName !== 'default') {
      document.body.classList.add(`theme-${themeName}`);
    }
    
    // 保存主题设置
    localStorage.setItem('quadrantTheme', themeName);
    
    // 更新主题选项的激活状态
    this.updateActiveTheme(themeName);
  }
  
  // 更新主题选项的激活状态
  updateActiveTheme(themeName) {
    // 移除所有主题选项的激活状态
    document.querySelectorAll('.theme-option').forEach(option => {
      option.classList.remove('active');
    });
    
    // 添加当前主题的激活状态
    const activeOption = document.querySelector(`.theme-option[data-theme="${themeName}"]`);
    if (activeOption) {
      activeOption.classList.add('active');
    }
  }
}

// UI控制器
class UIController {
  constructor(taskManager) {
    this.taskManager = taskManager;
    this.initializeEventListeners();
  }

  // 初始化事件监听器
  initializeEventListeners() {
    // 添加任务按钮事件
    const addButtons = document.querySelectorAll('.add-task-button');
    addButtons.forEach(button => {
      button.addEventListener('click', () => {
        const quadrant = button.getAttribute('data-quadrant');
        const formId = `add-form-${quadrant}`;
        document.getElementById(formId).classList.add('show');
      });
    });
    
    // 取消按钮事件
    const cancelButtons = document.querySelectorAll('.cancel-button');
    cancelButtons.forEach(button => {
      button.addEventListener('click', () => {
        const quadrant = button.getAttribute('data-quadrant');
        if (quadrant) {
          const formId = `add-form-${quadrant}`;
          document.getElementById(formId).classList.remove('show');
        }
      });
    });
    
    // 添加按钮事件
    const submitButtons = document.querySelectorAll('.add-button');
    submitButtons.forEach(button => {
      button.addEventListener('click', () => {
        const quadrant = button.getAttribute('data-quadrant');
        if (quadrant) {
          const formId = `add-form-${quadrant}`;
          const titleInput = document.querySelector(`#task-title-${quadrant}`);
          const descInput = document.querySelector(`#task-desc-${quadrant}`);
          const prioritySelect = document.querySelector(`#task-priority-${quadrant}`);
          const deadlineInput = document.querySelector(`#task-deadline-${quadrant}`);
          
          const title = titleInput.value.trim();
          
          if (title) {
            const taskData = {
              title: title,
              description: descInput.value.trim(),
              priority: prioritySelect.value,
              deadline: deadlineInput.value,
              quadrant: quadrant
            };
            
            this.taskManager.addTask(taskData);
            
            // 清空表单
            titleInput.value = '';
            descInput.value = '';
            prioritySelect.value = 'medium';
            deadlineInput.value = '';
            
            document.getElementById(formId).classList.remove('show');
          }
        }
      });
    });
    
    // 输入框回车事件
    const inputs = document.querySelectorAll('.task-input');
    inputs.forEach(input => {
      input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          e.preventDefault();
          const quadrant = input.getAttribute('data-quadrant');
          if (quadrant) {
            const formId = `add-form-${quadrant}`;
            const titleInput = document.querySelector(`#task-title-${quadrant}`);
            const descInput = document.querySelector(`#task-desc-${quadrant}`);
            const prioritySelect = document.querySelector(`#task-priority-${quadrant}`);
            const deadlineInput = document.querySelector(`#task-deadline-${quadrant}`);
            
            const title = titleInput.value.trim();
            
            if (title) {
              const taskData = {
                title: title,
                description: descInput.value.trim(),
                priority: prioritySelect.value,
                deadline: deadlineInput.value,
                quadrant: quadrant
              };
              
              this.taskManager.addTask(taskData);
              
              // 清空表单
              titleInput.value = '';
              descInput.value = '';
              prioritySelect.value = 'medium';
              deadlineInput.value = '';
              
              document.getElementById(formId).classList.remove('show');
            }
          }
        } else if (e.key === 'Escape') {
          const quadrant = input.getAttribute('data-quadrant');
          if (quadrant) {
            const formId = `add-form-${quadrant}`;
            document.getElementById(formId).classList.remove('show');
          }
        }
      });
    });
    
    // 下拉菜单事件
    const moreButton = document.getElementById('more-button');
    const dropdownMenu = document.getElementById('dropdown-menu');
    
    moreButton.addEventListener('click', () => {
      dropdownMenu.classList.toggle('show');
    });
    
    // 点击其他地方关闭下拉菜单
    window.addEventListener('click', (e) => {
      if (!e.target.matches('#more-button') && !e.target.closest('#more-button')) {
        if (dropdownMenu.classList.contains('show')) {
          dropdownMenu.classList.remove('show');
        }
      }
    });
    
    // 标记所有任务为已完成
    const markAllCompletedBtn = document.getElementById('mark-all-completed');
    markAllCompletedBtn.addEventListener('click', () => {
      this.taskManager.tasks.forEach(task => {
        if (!task.completed) {
          this.taskManager.toggleTaskStatus(task.id);
        }
      });
      dropdownMenu.classList.remove('show');
    });
    
    // 导出任务
    const exportTasksBtn = document.getElementById('export-tasks');
    exportTasksBtn.addEventListener('click', () => {
      const dataStr = JSON.stringify(this.taskManager.tasks, null, 2);
      const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
      
      const exportFileDefaultName = 'quadrant-tasks.json';
      
      const linkElement = document.createElement('a');
      linkElement.setAttribute('href', dataUri);
      linkElement.setAttribute('download', exportFileDefaultName);
      linkElement.click();
      
      dropdownMenu.classList.remove('show');
    });
    
    // 替换刷新按钮事件为主题按钮事件
    const themeButton = document.getElementById('theme-button');
    themeButton.addEventListener('click', () => {
      document.getElementById('theme-modal').classList.add('show');
      
      // 高亮当前选择的主题
      const currentTheme = localStorage.getItem('quadrantTheme') || 'default';
      this.taskManager.updateActiveTheme(currentTheme);
    });
    
    // 关闭主题模态框按钮
    const themeCloseButton = document.querySelector('#theme-modal .modal-close');
    themeCloseButton.addEventListener('click', () => {
      document.getElementById('theme-modal').classList.remove('show');
    });
    
    // 主题选择事件
    const themeOptions = document.querySelectorAll('.theme-option');
    themeOptions.forEach(option => {
      option.addEventListener('click', () => {
        const themeName = option.getAttribute('data-theme');
        this.taskManager.applyTheme(themeName);
        document.getElementById('theme-modal').classList.remove('show');
      });
    });
    
    // 编辑任务保存按钮事件
    const editSaveButton = document.getElementById('edit-save-button');
    editSaveButton.addEventListener('click', () => {
      const taskId = document.getElementById('edit-task-id').value;
      const title = document.getElementById('edit-task-title').value.trim();
      
      if (title) {
        const taskData = {
          title: title,
          description: document.getElementById('edit-task-desc').value.trim(),
          priority: document.getElementById('edit-task-priority').value,
          deadline: document.getElementById('edit-task-deadline').value
        };
        
        // 如果有象限选择器，添加象限数据
        if (document.getElementById('edit-task-quadrant')) {
          taskData.quadrant = document.getElementById('edit-task-quadrant').value || null;
        }
        
        this.taskManager.editTask(taskId, taskData);
        document.getElementById('edit-task-modal').classList.remove('show');
      }
    });
    
    // 编辑任务取消按钮事件
    const editCancelButton = document.getElementById('edit-cancel-button');
    editCancelButton.addEventListener('click', () => {
      document.getElementById('edit-task-modal').classList.remove('show');
    });
    
    // 编辑任务模态框关闭按钮
    const editCloseButton = document.querySelector('#edit-task-modal .modal-close');
    editCloseButton.addEventListener('click', () => {
      document.getElementById('edit-task-modal').classList.remove('show');
    });
    
    // 删除任务确认按钮事件
    const deleteConfirmButton = document.getElementById('delete-confirm-button');
    deleteConfirmButton.addEventListener('click', () => {
      const taskId = document.getElementById('delete-task-id').value;
      this.taskManager.deleteTask(taskId);
      document.getElementById('delete-confirm-modal').classList.remove('show');
    });
    
    // 删除任务取消按钮事件
    const deleteCancelButton = document.getElementById('delete-cancel-button');
    deleteCancelButton.addEventListener('click', () => {
      document.getElementById('delete-confirm-modal').classList.remove('show');
    });
    
    // 删除任务模态框关闭按钮
    const deleteCloseButton = document.querySelector('#delete-confirm-modal .modal-close');
    deleteCloseButton.addEventListener('click', () => {
      document.getElementById('delete-confirm-modal').classList.remove('show');
    });
    
    // 未分配任务按钮事件
    const unassignedButton = document.getElementById('unassigned-button');
    unassignedButton.addEventListener('click', () => {
      document.getElementById('unassigned-tasks-modal').classList.add('show');
    });
    
    // 关闭未分配任务模态框按钮
    const unassignedCloseButton = document.querySelector('#unassigned-tasks-modal .modal-close');
    unassignedCloseButton.addEventListener('click', () => {
      document.getElementById('unassigned-tasks-modal').classList.remove('show');
    });
    
    // 添加未分配任务按钮事件
    const addUnassignedButton = document.querySelector('.add-unassigned-button');
    addUnassignedButton.addEventListener('click', () => {
      document.getElementById('add-unassigned-modal').classList.add('show');
    });
    
    // 关闭添加未分配任务模态框按钮
    const addUnassignedCloseButton = document.querySelector('#add-unassigned-modal .modal-close');
    addUnassignedCloseButton.addEventListener('click', () => {
      document.getElementById('add-unassigned-modal').classList.remove('show');
    });
    
    // 添加未分配任务表单提交
    const unassignedAddButton = document.getElementById('unassigned-add-button');
    unassignedAddButton.addEventListener('click', () => {
      const title = document.getElementById('unassigned-task-title').value.trim();
      
      if (title) {
        const taskData = {
          title: title,
          description: document.getElementById('unassigned-task-desc').value.trim(),
          priority: document.getElementById('unassigned-task-priority').value,
          deadline: document.getElementById('unassigned-task-deadline').value
        };
        
        this.taskManager.addUnassignedTask(taskData);
        
        // 清空表单
        document.getElementById('unassigned-task-title').value = '';
        document.getElementById('unassigned-task-desc').value = '';
        document.getElementById('unassigned-task-priority').value = 'medium';
        document.getElementById('unassigned-task-deadline').value = '';
        
        document.getElementById('add-unassigned-modal').classList.remove('show');
      }
    });
    
    // 取消添加未分配任务
    const unassignedCancelButton = document.getElementById('unassigned-cancel-button');
    unassignedCancelButton.addEventListener('click', () => {
      document.getElementById('add-unassigned-modal').classList.remove('show');
    });
    
    // 分配任务确认按钮事件
    const assignSaveButton = document.getElementById('assign-save-button');
    assignSaveButton.addEventListener('click', () => {
      const taskId = document.getElementById('assign-task-id').value;
      const quadrant = document.getElementById('assign-task-quadrant').value;
      
      this.taskManager.assignTask(taskId, quadrant);
      document.getElementById('assign-task-modal').classList.remove('show');
    });
    
    // 分配任务取消按钮事件
    const assignCancelButton = document.getElementById('assign-cancel-button');
    assignCancelButton.addEventListener('click', () => {
      document.getElementById('assign-task-modal').classList.remove('show');
    });
    
    // 分配任务模态框关闭按钮
    const assignCloseButton = document.querySelector('#assign-task-modal .modal-close');
    assignCloseButton.addEventListener('click', () => {
      document.getElementById('assign-task-modal').classList.remove('show');
    });
    
    // 点击模态框外部关闭
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          modal.classList.remove('show');
        }
      });
    });

    // 筛选按钮事件
    const filterButton = document.querySelector('.filter-button');
    filterButton.addEventListener('click', () => {
      document.getElementById('filter-modal').classList.add('show');
      
      // 将当前筛选条件设置到表单
      this.setFilterFormValues();
    });
    
    // 关闭筛选模态框按钮
    const filterCloseButton = document.querySelector('#filter-modal .modal-close');
    filterCloseButton.addEventListener('click', () => {
      document.getElementById('filter-modal').classList.remove('show');
    });
    
    // 应用筛选按钮事件
    const filterApplyButton = document.querySelector('.filter-apply-button');
    filterApplyButton.addEventListener('click', () => {
      const filterOptions = this.getFilterFormValues();
      this.taskManager.applyFilter(filterOptions);
      document.getElementById('filter-modal').classList.remove('show');
    });
    
    // 重置筛选按钮事件
    const filterResetButton = document.querySelector('.filter-reset-button');
    filterResetButton.addEventListener('click', () => {
      this.clearFilterForm();
      this.taskManager.resetFilter();
      document.getElementById('filter-modal').classList.remove('show');
    });

    // 导入任务
    const importTasksBtn = document.getElementById('import-tasks');
    const importFileInput = document.getElementById('import-file-input');
    
    importTasksBtn.addEventListener('click', () => {
      importFileInput.click();
      dropdownMenu.classList.remove('show');
    });
    
    importFileInput.addEventListener('change', (e) => {
      if (e.target.files.length === 0) return;
      
      const file = e.target.files[0];
      const reader = new FileReader();
      
      reader.onload = (event) => {
        try {
          const taskData = JSON.parse(event.target.result);
          
          // 导入任务数据
          const result = this.taskManager.importTasks(taskData);
          
          // 显示导入结果
          if (result.success) {
            alert(result.message);
          } else {
            alert(result.message);
          }
          
          // 重置文件输入
          importFileInput.value = '';
        } catch (error) {
          console.error('读取文件失败:', error);
          alert('导入失败: 文件格式不正确');
          importFileInput.value = '';
        }
      };
      
      reader.onerror = () => {
        alert('读取文件时发生错误');
        importFileInput.value = '';
      };
      
      reader.readAsText(file);
    });
  }
  
  // 获取表单中的筛选值
  getFilterFormValues() {
    const filterOptions = {
      status: [],
      priority: [],
      deadline: [],
      dateRange: {
        from: null,
        to: null
      }
    };
    
    // 获取状态筛选
    document.querySelectorAll('input[name="status"]:checked').forEach(checkbox => {
      filterOptions.status.push(checkbox.value);
    });
    
    // 获取优先级筛选
    document.querySelectorAll('input[name="priority"]:checked').forEach(checkbox => {
      filterOptions.priority.push(checkbox.value);
    });
    
    // 获取截止日期筛选
    document.querySelectorAll('input[name="deadline"]:checked').forEach(checkbox => {
      filterOptions.deadline.push(checkbox.value);
    });
    
    // 获取自定义日期范围
    const fromDate = document.getElementById('filter-date-from').value;
    const toDate = document.getElementById('filter-date-to').value;
    
    if (fromDate && toDate) {
      filterOptions.dateRange.from = fromDate;
      filterOptions.dateRange.to = toDate;
    }
    
    return filterOptions;
  }
  
  // 设置筛选表单的初始值
  setFilterFormValues() {
    // 重置所有复选框
    document.querySelectorAll('#filter-modal input[type="checkbox"]').forEach(checkbox => {
      checkbox.checked = false;
    });
    
    // 设置状态筛选
    this.taskManager.filterOptions.status.forEach(status => {
      const checkbox = document.querySelector(`input[name="status"][value="${status}"]`);
      if (checkbox) checkbox.checked = true;
    });
    
    // 设置优先级筛选
    this.taskManager.filterOptions.priority.forEach(priority => {
      const checkbox = document.querySelector(`input[name="priority"][value="${priority}"]`);
      if (checkbox) checkbox.checked = true;
    });
    
    // 设置截止日期筛选
    this.taskManager.filterOptions.deadline.forEach(deadline => {
      const checkbox = document.querySelector(`input[name="deadline"][value="${deadline}"]`);
      if (checkbox) checkbox.checked = true;
    });
    
    // 设置自定义日期范围
    if (this.taskManager.filterOptions.dateRange.from) {
      document.getElementById('filter-date-from').value = this.taskManager.filterOptions.dateRange.from;
    } else {
      document.getElementById('filter-date-from').value = '';
    }
    
    if (this.taskManager.filterOptions.dateRange.to) {
      document.getElementById('filter-date-to').value = this.taskManager.filterOptions.dateRange.to;
    } else {
      document.getElementById('filter-date-to').value = '';
    }
  }
  
  // 清空筛选表单
  clearFilterForm() {
    document.querySelectorAll('#filter-modal input[type="checkbox"]').forEach(checkbox => {
      checkbox.checked = false;
    });
    
    document.getElementById('filter-date-from').value = '';
    document.getElementById('filter-date-to').value = '';
  }
}

// 当DOM加载完成时初始化应用
document.addEventListener('DOMContentLoaded', () => {
  const taskManager = new TaskManager();
  const uiController = new UIController(taskManager);
}); 